import { defineStore } from 'pinia';

import { login, userInfo } from '@/api/auth';
import type { LoginParam } from '@/api/model/loginModel';
import { TOKEN_NAME } from '@/config/global';
import { usePermissionStore } from '@/store';
import type { UserInfo } from '@/types/interface';

const InitUserInfo: UserInfo = {
  name: '', // 用户名，用于展示在页面右上角头像处
  roles: [], // 前端权限模型使用 如果使用请配置modules/permission-fe.ts使用
};

export const useUserStore = defineStore('user', {
  state: () => ({
    token: localStorage.getItem(TOKEN_NAME), // 默认token不走权限
    userInfo: { ...InitUserInfo },
  }),
  getters: {
    roles: (state) => {
      return state.userInfo?.roles;
    },
  },
  actions: {
    async login(userInfo: Record<string, unknown>) {
      const res: any = await login({
        username: userInfo.account,
        password: userInfo.password,
      } as LoginParam);
      if (res.code === 200) {
        this.token = res.data;
        localStorage.setItem(TOKEN_NAME, res.data);
      } else {
        throw res;
      }
    },
    async getUserInfo() {
      const res: any = await userInfo();
      const { code } = res;
      if (code === 200) {
        this.userInfo = {
          name: res.data.username,
          roles: res.data.roles,
        };
      } else {
        throw res;
      }
    },
    async logout() {
      localStorage.removeItem(TOKEN_NAME);
      this.token = '';
      this.userInfo = { ...InitUserInfo };
    },
  },
  persist: {
    afterRestore: () => {
      const permissionStore = usePermissionStore();
      permissionStore.initRoutes();
    },
    key: 'user',
    paths: ['token'],
  },
});
